#include "decrypter.h"
#include <string.h>

/**
 * Decyphers the string s.
 *
 * @param[in]	s              The cyphered data
 * @param[in]	size		      The size of the data.
 *
 * @return	The decyphered data.
 */
static void myDecryptionAlgo (int *s, long size);

/**
 * Compares two letterStat.
 *
 * @param[in]	f1   A letterStat.
 * @param[in]	f2   Another letterStat.
 *
 * @return	Lower than zero if f2 has greater frequency than f1, greater than zero if f1
 *          has greater frequency than f2 or zero if they are equal.
 */
static int letterStatCmp (const void *f1, const void * f2);

// testeo para varios vigenere
int
main(void)
{
   int *s, i;
   long size;
   char * vigFiles[12] = {"../testFiles/s01-3-V.txt","../testFiles/s02-2-V.txt",
		   "../testFiles/s03-3-V.txt","../testFiles/s04-2-V.txt",
		   "../testFiles/s05-3-V.txt","../testFiles/s06-3-V.txt",
		   "../testFiles/s07-1-V.txt","../testFiles/s08-1-V.txt",
		   "../testFiles/s09-2-V.txt","../testFiles/s10-3-V.txt",
		   "../testFiles/s11-2-V.txt","../testFiles/s12-2-V.txt",};
   char * transFiles[12] = {"../testFiles/s01-1-T.txt","../testFiles/s02-1-T.txt",
   		   "../testFiles/s03-1-T.txt","../testFiles/s04-3-T.txt",
   		   "../testFiles/s05-2-T.txt","../testFiles/s06-1-T.txt",
   		   "../testFiles/s07-2-T.txt","../testFiles/s08-3-T.txt",
   		   "../testFiles/s09-1-T.txt","../testFiles/s10-2-T.txt",
   		   "../testFiles/s11-1-T.txt","../testFiles/s12-3-T.txt",};
   
   for (i = 0; i < 12; i++)
   {
	   if ( (s = readFile(transFiles[i], &size) ) == NULL)
	   {
		   printf("Error en lectura\n");
		   return 1;
	   }
	
	   /*printf("Longitud %ld Mapeo de numeros:\n", size);
	   for (i=0; i<size; i++)
	      printf("%d\n", s[i]);
	   printf("--------------------\n");*/
	
	   myDecryptionAlgo(s, size);
	   getchar();
   }

   return 0;
   
}

static int
letterStatCmp (const void *f1, const void * f2)
{
   return (*((letterStat*)f2)).freq - (*((letterStat*)f1)).freq;
}

static void
myDecryptionAlgo (int *s, long size)
{
   alphabetArray cypherFreq;
   
   /* The frequencies are computed */
   computeFrequencies(s, size, &cypherFreq);
   /*int i;
   printf("Frecuencias:\n");
   for (i = 0; i < ALPHABET_NUM; i++)
      printf("%d \t %g\n", cypherFreq[i].c, cypherFreq[i].freq);
   printf("--------------------\n");*/
   
   
   if (checkTransposition(cypherFreq, sortedSpanishFrequencies, TRANSPOSITION_TOP_CHECK, 0.7))
   {
      printf("Ejecuto transposicion!.\n");
      solveTranspo( s,  size);
   }
   else if (checkCesar (cypherFreq, size, 80))
   {
      printf("Ejecuto Cesar!.\n");
      solveCesar(s, size, cypherFreq, NUMBER_SOL);
   }
   else
   {
      printf("Ejecuto Vigenere!.\n");
      solveVigenere(s, size);
   }
   
   free(s);
         
   return;
}